/** 账号相关控制器 */
import { Inject, Controller, Post, Body, Get, Query } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { AccountService } from '../../service/user/Account';
import { createErrorResponse, createSuccessResponse } from '../request';
import { auth, rs } from 'qiniu';

const AK = 'L5VZ0hd6EmEupQBkw956FrX9ugha-NUzCeCDTiOC'
const SK = 'cnY6vq3vhFKZMo96Szfr8oeW-kn5L2vdmZZvzU3y'

@Controller('/api')
export class AccountController {
  @Inject()
  ctx: Context;

  @Inject()
  accountService: AccountService;

  @Get('/getAK')
  async getAk() {
    const mac = new auth.digest.Mac(AK, SK);
    const options = {
      scope: 'dlc-space',
      expires: 7200,
    }
    const putPolicy = new rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);
    console.log(uploadToken);
    return uploadToken;
  }

  @Post('/get_user')
  async getUser(@Body() body) {
    console.log(body);
    return {};
  }

  @Get('/getAllUsers')
  async getAllUsers(@Query() query) {
    return this.accountService.getAllUsers();
  }

  /** 注册用户 */
  @Post('/register')
  async register(@Body() body) {
    const { identity, username, password } = body;
    if (identity && username && password) {
      const result = await this.accountService.register({
        identity,
        username,
        password
      })
      if (result.success) {
        return createSuccessResponse("创建成功", result.data);
      } else {
        return createErrorResponse(result.msg);
      }
    } else {
      return createErrorResponse("参数校验失败");
    }
  }

  /** 登录 */
  @Post('/login')
  async login(@Body() body) {
    const { username, password } = body;
    if (username && password) {
      const result = await this.accountService.login({
        username,
        password
      })
      if (result.success) {
        return createSuccessResponse(result.msg, result.data)
      } else {
        return createErrorResponse(result.msg)
      }
    }
    return createErrorResponse("参数校验失败")
  }

}